#include "QLibSsh/sshsession.h"

#include <QLibSsh/QLibSsh_global.h>

SshSession::SshSession(const std::string& user, const std::string& host, const int port, std::string password)
    : SharePtr (ssh_new())
{
    ssh_options_set(mPtr, SSH_OPTIONS_USER, user.c_str());
    ssh_options_set(mPtr, SSH_OPTIONS_HOST, host.c_str());
    ssh_options_set(mPtr, SSH_OPTIONS_PORT, &port);
    mPassword = std::move(password);
}

SshSession::SshSession()
    : SharePtr (nullptr)
{}

SshSession::~SshSession() {
    if (mPtr == nullptr) {
        return;
    }
    mRefCount->fetch_sub(1, std::memory_order_relaxed);
    if (mRefCount->load(std::memory_order_relaxed) == 0) {
        ssh_free(mPtr);
    }
    qDebug() << "SshSession::~SshSession";
    mPtr = nullptr;
    mRefCount = nullptr;
}

bool SshSession::connect() const {
    auto result = ssh_connect(mPtr);
    if (result != SSH_OK) {
        qCritical("Error connecting to localhost: %s", ssh_get_error(mPtr));
        return false;
    }

    // 目前只采用password进入
    result = ssh_userauth_password(mPtr, nullptr, mPassword.c_str());
    if (result != SSH_AUTH_SUCCESS) {
        qCritical("Error authenticating with password: %s", ssh_get_error(mPtr));
        ssh_disconnect(mPtr);
        return false;
    }
    return true;
}
